package com.chat.consumer.rpc;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.base64.Base64Encoder;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @Auther created by haoteng on 2019/08/16
 */
//@Component
public class NettyClient {
    public static Semaphore semaphore = new Semaphore(1);

    private String ip;

    private Integer port;

    public static Channel channel;

    ExecutorService exec = Executors.newSingleThreadExecutor();


    public NettyClient(String ip, Integer port) {
        this.ip = ip;
        this.port = port;
        exec.execute(new NettyClientStart());
    }

    private void start() {
        try {
            semaphore.acquire();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {

                            socketChannel.pipeline().addLast(new DemoClientOutChannelHandler());
                            socketChannel.pipeline().addLast(new Base64Encoder());
                            socketChannel.pipeline().addLast(new DemoClientInChannelHandler());
                        }
                    });
            ChannelFuture channelFuture = b.connect(ip, port).sync();

            channel = channelFuture.channel();
            System.out.println(Thread.currentThread().getName() + ",客户端发起异步连接..........");
            semaphore.release();
            /**等待客户端链路关闭*/
            channelFuture.channel().closeFuture().sync();
            System.out.println(Thread.currentThread().getName() + ",客户端连接关闭");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }

    }

    private class NettyClientStart implements Runnable {

        @Override
        public void run() {
            start();
        }
    }
}
